<template>
  <div id="shopping_cart">
    <!-- 头部组件 -->
    <div class="top">
      <top></top>
    </div>

    <!-- 中部组件 -->

    <div class="center">
      <!-- 购物车中的商品展示 -->
      <div class="shooping_cart_tab">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="全部商品" name="first">
            <el-table
              ref="multipleTable"
              :data="tableData"
              style="width: 100%"
              @selection-change="handleSelectionChange"
              max-height="550px"
            >
              <el-table-column
                type="selection"
                min-width="55"
                header-align="center"
                align="center"
              ></el-table-column>
              <el-table-column
                type="index"
                label="#"
                min-width="55"
                header-align="center"
                align="center"
              ></el-table-column>
              <el-table-column
                label="商品信息"
                min-width="120"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  <!-- <img :src="scope.row.img_url">
                  <span>{{scope.row.describe}}</span>-->
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="scope.row.describe"
                    placement="top"
                  >
                    <img class="table-image" :src="scope.row.img_url" />
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column
                label="单价"
                min-width="120"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  <span style="color: red">￥{{ scope.row.price.toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="数量"
                min-width="120"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.number"
                    size="mini"
                    @change="handleChangeGoodsNumber(scope)"
                    :min="1"
                    :max="10"
                    label="数量"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                label="金额"
                min-width="120"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  <span style="color: red"
                    >￥{{ (scope.row.price * scope.row.number).toFixed(2) }}</span
                  >
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                label="操作"
                fixed="right"
                min-width="120"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  <el-tooltip class="item" effect="dark" content="删除" placement="top">
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      circle
                      @click="delectShoppingCartGoods(scope)"
                    ></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <!-- <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="1"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="5"
              layout="total, sizes, prev, pager, next, jumper"
              :total="10"
            >
            </el-pagination>-->
          </el-tab-pane>
        </el-tabs>
        <!-- 按钮 -->
        <el-card shadow="always" class="check_out_wrap">
          <el-row type="flex" justify="end">
            <el-col :span="2" :pull="14">
              <el-button type="primary" size="mini" round @click="select_all()"
                >全选</el-button
              >
            </el-col>
            <el-col :span="6" :pull="1">
              <span class="sum_srap" style="font-size: 20px">
                合计（不含运费）：
                <span class="sum" style="color: red" v-if="sum == 0">￥{{ sum }}</span>
                <span class="sum" style="color: red" v-else>￥{{ sum.toFixed(2) }}</span>
              </span>
            </el-col>
            <el-col :span="2">
              <el-button type="danger" size="mini" round @click="goCheckOut()"
                >结算</el-button
              >
            </el-col>
          </el-row>
        </el-card>
      </div>
    </div>

    <!-- 底部组件 -->
    <div class="foot">
      <bottom></bottom>
    </div>

    <!-- 点击结算按钮时弹出的对话框 -->
    <el-dialog
      title="订单"
      :visible.sync="orderDialogVisible"
      width="60%"
      center
      top="5vh"
    >
      <el-table
        ref="multipleOrderTable"
        :data="multipleSelection"
        style="width: 100%"
        max-height="500px"
      >
        <el-table-column
          type="index"
          label="#"
          min-width="55"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column
          label="商品信息"
          min-width="120"
          header-align="center"
          align="center"
        >
          <template slot-scope="scope">
            <!-- <img :src="scope.row.img_url">
            <span>{{scope.row.describe}}</span>-->
            <el-tooltip
              class="item"
              effect="dark"
              :content="scope.row.describe"
              placement="top"
            >
              <img class="table-image" :src="scope.row.img_url" />
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          label="单价"
          min-width="120"
          header-align="center"
          align="center"
        >
          <template slot-scope="scope">
            <span style="color: red">￥{{ scope.row.price.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="数量"
          min-width="120"
          header-align="center"
          align="center"
        >
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.number"
              size="mini"
              @change="handleChangeGoodsNumber(scope)"
              :min="1"
              :max="10"
              label="数量"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="金额"
          min-width="120"
          header-align="center"
          align="center"
        >
          <template slot-scope="scope">
            <span style="color: red"
              >￥{{ (scope.row.price * scope.row.number).toFixed(2) }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="操作"
          fixed="right"
          min-width="120"
          header-align="center"
          align="center"
        >
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="删除" placement="top">
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="delectShoppingCartGoods(scope)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <span class="sum_srap" style="font-size: 20px">
          合计（不含运费）：
          <span class="sum" style="color: red" v-if="sum == 0">￥{{ sum }}</span>
          <span class="sum" style="color: red" v-else>￥{{ sum.toFixed(2) }}</span>
        </span>
        <br />
        <br />
        <el-button @click="checkOutDialogButtonCancel()" size="mini">取 消</el-button>
        <el-button type="primary" @click="checkOutDialogButtonConfirm()" size="mini"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 结算 ==> 对话框 -->
    <el-dialog title="结算" :visible.sync="dialogCheckOutIsVisible" width="450px">
      <el-form ref="checkOutForm" v-model="checkOutForm" label-width="auto" size="mini">
        <el-form-item label="商品总价:">
          <span class="totalPrice">￥ {{ checkOutForm.totalPrice }} 元</span>
        </el-form-item>
        <el-form-item label="请选择付款方式:" prop="paymentOption">
          <el-select placeholder="请选择付款方式" v-model="checkOutForm.paymentOption">
            <el-option
              v-for="(item, index) in paymentOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="checkOutCancel()">取消</el-button>
          <el-button type="danger" @click="checkOutConfirm()">立即购买</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 微信支付对话框 -->
    <el-dialog
      class="paymentDialog"
      title="微信支付"
      :visible.sync="weiXinPaymentDialogIsVisble"
      width="30%"
    >
      <el-form v-model="checkOutForm" label-width="auto" size="mini">
        <el-form-item label="商品总价:">
          <span class="totalPrice">￥ {{ checkOutForm.totalPrice }} 元</span>
        </el-form-item>
        <el-form-item label="请扫码支付:" prop="img">
          <img src="../../assets/image_payment/weixin.png" class="paymentImage" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="paymentDialogCancel()">取 消</el-button>
        <el-button type="primary" @click="paymentDialogConfirm()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 支付宝支付对话框 -->
    <el-dialog
      class="paymentDialog"
      title="支付宝支付"
      :visible.sync="zhiFuBaoPaymentDialogIsVisble"
      width="30%"
    >
      <el-form v-model="checkOutForm" label-width="auto" size="mini">
        <el-form-item label="商品总价:">
          <span class="totalPrice">￥ {{ checkOutForm.totalPrice }} 元</span>
        </el-form-item>
        <el-form-item label="请扫码支付:" prop="img">
          <img src="../../assets/image_payment/zhifubao.jpg" class="paymentImage" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="paymentDialogCancel()">取 消</el-button>
        <el-button type="primary" @click="paymentDialogConfirm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//  引入头部组件
import top from "../../components/header";
//  引入底部组件
import bottom from "../../components/footer";

//  导入封装好的后台接口函数
import {
  selectShoppingCartItemByPaging,
  deleteShoppingCartGoodsItem,
  updateShoppingCartItem,
} from "../../api/ShoppingCart/index.js";
export default {
  components: {
    top,
    bottom,
  },
  mounted() {
    // 页面创建开始时的准备工作

    //  获取当前用户的基本信息
    this.userInfo = JSON.parse(sessionStorage.getItem("userInfo"));

    //  查询数据库中的购物车商品的信息及数量
    this.funSelectShoppingCartItemByPaging();
  },
  data() {
    return {
      dialogCheckOutIsVisible: false,
      weiXinPaymentDialogIsVisble: false,
      zhiFuBaoPaymentDialogIsVisble: false,
      checkOutForm: {
        totalPrice: 0,
        paymentOption: "weixin",
      },
      paymentOptions: [
        { label: "微信", value: "weixin" },
        { label: "支付宝", value: "zhifubao" },
      ],
      //  当前用户的信息
      userInfo: "",
      //  默认激活项 （默认激活第一项）
      activeName: "first",
      //  选中商品的总价值（默认总价值为 0）
      sum: 0.0,
      //  是否将选中购物车中的所有商品 （默认不选择）
      is_select_all: false,
      //  订单对话框是否显示（默认为不显示）
      orderDialogVisible: false,
      //  表格中的数据
      tableData: [
        {
          id: "",
          img_url:
            "https://img.alicdn.com/bao/uploaded/i4/2090337761/O1CN01sJc9Is27CaUbkHstn_!!2090337761.jpg_80x80.jpg",
          describe: "顺丰技嘉RTX3090 24G高端台式电脑主机游戏独立显卡GAMING OC猎鹰",
          price: 15999.0,
          number: 1,
        },
        {
          //  商品的 id
          id: "",
          //  商品图片的 地址
          img_url:
            "https://img.alicdn.com/bao/uploaded/i3/654519625/O1CN01FfASKD2KyIlJyz5zT_!!654519625.jpg_80x80.jpg",
          //  商品的描述
          describe:
            "Asus/华硕B450/B550 搭AMD锐龙R5 3500X 全新正品游戏办公重炮手主板CPU套装超R5 2600电竞板U套装旗舰店",
          //  商品的价格
          price: 1559.0,
          //  商品须有购买的数量
          number: 1,
        },
        {
          id: "",
          img_url:
            "https://img.alicdn.com/bao/uploaded/i1/3171286391/O1CN01ZAntkK1x57sEL1RmH_!!3171286391.jpg_80x80.jpg",
          describe: "铭瑄GTX1660/1660s super终结者电竞之心6G独立电脑主机游戏显卡",
          price: 2149.0,
          number: 1,
        },
        {
          id: "",
          img_url:
            "https://img.alicdn.com/bao/uploaded/i4/3817310001/O1CN01FYRMf81BsV1JYAd6t_!!3817310001.jpg_80x80.jpg",
          describe: "酷冷至尊 MB520机箱 台式机箱中塔机箱 侧透ATX主机机箱 电脑机箱",
          price: 279.0,
          number: 1,
        },
        {
          id: "",
          img_url:
            "https://img.alicdn.com/bao/uploaded/i1/3817310001/O1CN01Utof6r1BsV1LdSgZB_!!3817310001.jpg_80x80.jpg",
          describe: "酷冷至尊 暴雪t400i散热器 台式机cpu 电脑散热器4热管LED风扇",
          price: 199.0,
          number: 1,
        },
        {
          id: "",
          img_url:
            "https://img.alicdn.com/bao/uploaded/i1/3171286391/O1CN01ZAntkK1x57sEL1RmH_!!3171286391.jpg_80x80.jpg",
          describe: "英特尔酷睿i5 10600K/10600KF盒装搭铭瑄B460M电竞之心挑战者主板CPU套装",
          price: 1999.0,
          number: 1,
        },
        {
          id: "",
          img_url:
            "https://img.alicdn.com/bao/uploaded/i3/3171286391/O1CN01hx8RHn1x57sAo9xje_!!3171286391.jpg_80x80.jpg",
          describe: "AMD锐龙R5 3600 3600X CPU搭配铭瑄B550M终结者主板主板板U游戏套装",
          price: 1819.0,
          number: 1,
        },
      ],
      //  选择的多项商品 （默认没有多选）
      multipleSelection: [],
    };
  },
  methods: {
    /**
     * 修改当前购物车中的记录（购物车中商品的数量）
     */
    funUpdateShoppingCartItem(item = { goodsId: null, goodsNumber: null, userId: null }) {
      if (item.goodsId !== null && item.goodsNumber != null && item.userId !== null) {
        updateShoppingCartItem(item).then(
          (res) => {
            // console.log(res);
          },
          (err) => {
            console.log(err);
          }
        );
      }
    },
    /**
     * 从指定的用户(传入用户主键userId，默认为当前用户)的购物车中删除指定的商品（传入商品主键goodsId）
     */
    async funDeleteShoppingCartGoodsItem(goodsId, userId = this.userInfo.id) {
      //  将数据转换为数据对象（后台要求的格式）
      let data = { goodsId: goodsId, userId: userId };

      //  调用后台接口，删除数据库中的记录
      await deleteShoppingCartGoodsItem(data).then(
        (res) => {
          //  console.log(res);
        },
        (err) => {
          console.log(err);
        }
      );
    },
    /**
     * 查询当前用户的所有购物车中的商品
     */
    async funSelectShoppingCartItemByPaging(
      data = { pageSize: 10, pageNumber: 1, userId: this.userInfo.id }
    ) {
      await selectShoppingCartItemByPaging(data).then(
        (res) => {
          let templist = res.list;
          templist.forEach((item, index) => {
            this.tableData.splice(0, 0, item);
          });
        },
        (err) => {
          console.log(err);
        }
      );
    },

    select_all() {
      //  是否全选所有购物车中的商品
      this.is_select_all = !this.is_select_all;

      this.toggleSelection();
    },
    delectShoppingCartGoods(scope) {
      /**
       * 删除购物车中的商品
       */
      //  console.log(scope);

      //  获取需要删除的对象
      let shoppingCartItem = scope.row;

      if (shoppingCartItem.id != "") {
        //  如果当前对象在数据库中存在记录（主键不为空）

        //  获取对象的主键
        const goodsId = shoppingCartItem.id;

        const userId = this.userInfo.id;

        //  console.log(goodsId, userId);

        // 每次删除购物车中的商品都要去数据库中修改记录
        this.funDeleteShoppingCartGoodsItem(goodsId, userId);
      }

      //    前端从 table 中删除商品
      this.tableData.splice(scope.$index, 1);
    },
    handleClick(tab, event) {
      // 点击 tab 触发
      //console.log(tab, event);
    },
    toggleSelection() {
      //  手动点击全选按钮时触发
      if (this.is_select_all) {
        this.$refs.multipleTable.clearSelection();
        this.tableData.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      //  选择修改时触发
      this.multipleSelection = val;
      this.getSum();
    },
    getSum() {
      //  获得总金额
      this.sum = 0.0;
      this.multipleSelection.forEach((item) => {
        this.sum += item.price * item.number;
      });
    },
    handleChangeGoodsNumber(scope) {
      //  计数器被点击时
      //console.log(scope.row);

      //  获取当前被修改的对象详细信息
      const tempItem = scope.row;

      //  每次点击一次计数器，就去修改数据库中的记录
      if (scope.row.id !== "") {
        //  创建后台接口所需要的数据结构
        let shoppingCartItem = {
          //  goodsId: 商品主键（商品的唯一标识）
          //  goodsNumber: 商品数量
          //  userId: 用户主键（当前用户的唯一标识）
          goodsId: tempItem.id,
          goodsNumber: tempItem.number,
          userId: this.userInfo.id,
        };

        //  修改数据库中的记录
        this.funUpdateShoppingCartItem(shoppingCartItem);
      }

      //  获取选中的商品的总价
      this.getSum();
    },
    goCheckOut() {
      //  打开订单对话框
      this.orderDialogVisible = true;
    },
    /**
     * 计算对话框中的取消按钮被点击时触发
     */
    checkOutDialogButtonCancel() {
      //  提示
      this.$notify({
        /* 指定消息的标题 */
        title: "结算",
        /* 指定消息的内容 */
        message: "取消结算",
        /* 指定消息出现的位置 */
        position: "top-right",
        /* 指定消息的类型 */
        type: "warning",
        /* 持续两秒钟 */
        duration: 2 * 1000,
      });

      //  关闭订单对话框
      this.orderDialogVisible = false;
    },
    /**
     * 结算对话框中的确认按钮被点击时触发
     */
    checkOutDialogButtonConfirm() {
      //  关闭订单对话框
      this.orderDialogVisible = false;

      //  获取总价格
      this.checkOutForm.totalPrice = this.sum;

      //  打开选择支付方式对话框
      this.dialogCheckOutIsVisible = true;
    },
    /**
     * 选择支付方式对话框中的取消按钮被点击时触发
     */
    checkOutCancel() {
      //  提示
      this.$notify({
        /* 指定消息的标题 */
        title: "结算",
        /* 指定消息的内容 */
        message: "取消结算",
        /* 指定消息出现的位置 */
        position: "top-right",
        /* 指定消息的类型 */
        type: "warning",
        /* 持续两秒钟 */
        duration: 2 * 1000,
      });

      //  关闭选择支付方式对话框
      this.dialogCheckOutIsVisible = false;
    },
    /**
     * 选择支付方式对话框中的立即购买按钮被点击时触发
     */
    checkOutConfirm() {
      //  判断用户选择的支付方式
      if (this.checkOutForm.paymentOption === "weixin") {
        //  选择微信支付，打开微信支付对话框
        this.weiXinPaymentDialogIsVisble = true;
      } else {
        //  选择支付宝支付，打开支付宝支付对话框
        this.zhiFuBaoPaymentDialogIsVisble = true;
      }
      //  关闭选择支付方式对话框
      this.dialogCheckOutIsVisible = false;
    },
    /**
     * 支付对话框中确认按钮点击时触发
     */
    paymentDialogConfirm() {
      //  关闭付款页面
      this.zhiFuBaoPaymentDialogIsVisble = false;
      this.weiXinPaymentDialogIsVisble = false;

      // 将已经购买了的商品删除购物车
      console.log(this.multipleSelection);

      //  遍历每一个被选中的商品
      this.multipleSelection.forEach((item, index) => {
        //  取出商品名称
        const name = item.describe;

        //  遍历显示的数组
        this.tableData.forEach(async (tItem, tIndex) => {
          //  取出商品名称
          const tName = tItem.describe;

          if (name === tName) {
            //  找到了需要删除的商品

            if (tItem.id !== "") {
              //  取出商品的主键
              const goodsId = tItem.id;

              //  从数据库中删除商品，刷新后不会恢复
              await this.funDeleteShoppingCartGoodsItem(goodsId);

              this.tableData.splice(tIndex, 1);
            }

            //  从前端删除商品，删除后刷新会恢复
            this.tableData.splice(tIndex, 1);
          }
        });
      });

      // 提示购买成功
      this.$notify({
        /* 指定消息的标题 */
        title: "支付",
        /* 指定消息的内容 */
        message: "支付成功",
        /* 指定消息出现的位置 */
        position: "top-right",
        /* 指定消息的类型 */
        type: "success",
        /* 持续两秒钟 */
        duration: 2 * 1000,
      });
    },
    /**
     * 支付对话框中取消按钮点击时触发
     */
    paymentDialogCancel() {
      //  关闭付款页面
      this.zhiFuBaoPaymentDialogIsVisble = false;
      this.weiXinPaymentDialogIsVisble = false;

      //  提示支付失败
      this.$notify({
        /* 指定消息的标题 */
        title: "支付",
        /* 指定消息的内容 */
        message: "支付失，请稍后重试",
        /* 指定消息出现的位置 */
        position: "top-right",
        /* 指定消息的类型 */
        type: "warning",
        /* 持续两秒钟 */
        duration: 2 * 1000,
      });
    },
  },
};
</script>

<style>
.shooping_cart_tab {
  margin: 10px auto;
  min-height: 600px;
  width: 1200px;
  min-width: 1200px;
  max-width: 1200px;
  background-color: white;
}

.center {
  padding: 0px 20px;
}

.check_out_wrap {
  margin: 10px 0px;
}

.foot {
  width: 100%;
}
.table-image {
  width: 80px;
  height: 80px;
}
</style>
